package memorphic.slide.plugin.wizards;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Properties;

import org.eclipse.ant.core.AntRunner;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;


/**
 * This is a sample new wizard. Its role is to create a new file 
 * resource in the provided container. If the container resource
 * (a folder or a project) is selected in the workspace 
 * when the wizard is opened, it will accept it as the target
 * container. The wizard creates one file with the extension
 * "slide". If a sample multi-page editor (also available
 * as a template) is registered for the same extension, it will
 * be able to open it.
 */

public class ConvertToSlideWizard extends Wizard implements INewWizard {
	private ConvertToSlide page;
	private ISelection selection;

	/**
	 * Constructor for GenerateSlideWizard.
	 */
	public ConvertToSlideWizard() {
		super();
		setNeedsProgressMonitor(true);
	}
	
	/**
	 * Adding the page to the wizard.
	 */

	public void addPages() {
		page = new ConvertToSlide(selection);
		addPage(page);
	}

	/**
	 * This method is called when 'Finish' button is pressed in
	 * the wizard. We will create an operation and run it
	 * using wizard as execution context.
	 */
	public boolean performFinish() {
		final String projectName = page.getProjectName();
		final String projectDirectory = page.getProjectDirectory(projectName);
		final String classPrefix = page.getClassPrefix();
		final String packageDirectory = projectDirectory + "/src/" + page.getProjPackage().replace(".", "/");
		final String packageID = page.getProjPackage();
		final String libraryDirectory = page.getProjectDirectory(projectName) + "/libs";
		IRunnableWithProgress op = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doFinish(projectDirectory,
							 projectName,
							 classPrefix,
							 packageDirectory,
							 packageID,
							 libraryDirectory,
							 monitor);
				} catch (CoreException e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			return false;
		} catch (InvocationTargetException e) {
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * The worker method. It will find the container, create the
	 * files, and refresh the workspace.
	 */
	private void doFinish(
		String projectDirectory,
		String projectName,
		String classPrefix,
		String packageDirectory,
		String packageID,
		String libraryDirectory,
		IProgressMonitor monitor)
		throws CoreException {
		final Properties props = new Properties();
		props.put("projectDirectory", projectDirectory);
		props.put("projectName", projectName);
		props.put("classPrefix", classPrefix);
		props.put("packageDirectory", packageDirectory);
		props.put("packageID", packageID);
		props.put("libraryDirectory", libraryDirectory);
		try
		{
			URL fileURL = FileLocator.toFileURL(Platform.getBundle("memorphic.slide.plugin").getEntry("/resources/slide-project-setup.xml"));
			
			AntRunner runner = new AntRunner();
			String path = fileURL.getPath();
			System.out.println(path);
			runner.setBuildFileLocation(path);
			runner.addUserProperties(props);
			runner.run(monitor);
		}
		catch (IOException e)
		{
			System.out.println("ant failed: " + e.getCause().getMessage());
			throw new CoreException(Status.CANCEL_STATUS);
		}
		
		generateSlideProjectFile(ResourcesPlugin.getWorkspace().getRoot().getProject(projectName),props);
		
		ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, monitor);
	}
	
	/**
	 * We will accept the selection in the workbench to see if
	 * we can initialize from it.
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection) {
		this.selection = selection;
	}
	
	private void generateSlideProjectFile(IProject project, Properties props) {
		try {
			URL u = Platform.getBundle("memorphic.slide.plugin").getEntry("/resources/slide/.slideProject");
			URL fileURL = FileLocator.toFileURL(u);
			BufferedReader in = new BufferedReader(new FileReader(fileURL.getPath()));
			String path = project.getLocation().toOSString();
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(path + "/.slideProject")));
			String s;
			while ((s = in.readLine()) != null)
			{
				if (s.equals("packageID"))
				{
					out.println(s + ":" + props.getProperty("packageID"));
					continue;
				}
				if (s.equals("baseView"))
				{
					out.println(s + ":" + props.getProperty("classPrefix") + "View.as");
					continue;
				}
				if (s.equals("appMain"))
				{
					out.println(s + ":" + props.getProperty("classPrefix") + "AppMain.as");
					continue;
				}
				if (s.equals("appProps"))
				{
					out.println(s + ":" + props.getProperty("classPrefix") + "AppProps.as");
					continue;
				}
				if (s.equals("iAppProps"))
				{
					out.println(s + ":" + "I" + props.getProperty("classPrefix") + "AppProps.as");
					continue;
				}
				if (s.equals("stateManager"))
				{
					out.println(s + ":" + props.getProperty("classPrefix") + "StateManager.as");
					continue;
				}
			}
			out.close();
		}
		catch (IOException e) {
			// TODO: handle exception
			System.out.println(e.getMessage());
		}
	}
	
//	private Boolean checkIfAlreadySlide() {
//		ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(""));
//		
//		return false;
//	}
}